<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加秒杀' : '编辑秒杀'" center :before-close="beforeClose">
            <el-form :model="seckForm" ref="seckRef" :rules="rules">
                <el-form-item label="活动名称" :label-width="formLabelWidth" prop="title">
                    <el-input v-model="seckForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="活动期限" :label-width="formLabelWidth">
                    <el-date-picker v-model="value2" type="daterange" unlink-panels range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" :size="size" />
                </el-form-item>
                <el-form-item label="一级分类" :label-width="formLabelWidth">
                    <el-select v-model="seckForm.first_cateid" placeholder="请选择分类" @change="changeCate(false)">
                        <el-option v-for="item in store.getters['cate/getCate']" :key="item.id" :label="item.catename"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth">
                    <el-select v-model="seckForm.second_cateid" placeholder="请选择分类">
                        <el-option v-for="item in cateArr.data" :key="item.id" :label="item.catename" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品" :label-width="formLabelWidth">
                    <el-select v-model="seckForm.goodsid" placeholder="请选择商品">
                        <el-option v-for="item in store.getters['goods/getGoods']" :key="item.id" :label="item.goodsname"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="seckForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(seckRef)">取消</el-button>
                    <el-button type="primary" @click="sure(seckRef)">添加</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { ref, defineProps, defineEmits, reactive, defineExpose } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { seckAdd, seckEdit, seckInfo } from '../../request/api'
import { useStore } from 'vuex'
let store = useStore()

//id的值先为0
var newId = 0

let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})


//子传父
let emit = defineEmits(['cancel'])

let seckForm = ref<any>({
    title: '',//限时秒杀名称
    begintime: '',//开始时间
    endtime: '',//结束时间
    first_cateid: '',//商品一级分类编号
    second_cateid: '',//商品二级分类编号
    goodsid: '',//商品编号
    status: 1,//状态   1正常2禁用
})

//封装一个确定事件
let seckRef = ref<FormInstance>()

//关闭x事件
const beforeClose = (done: any) => {
    done()
    cancel(seckRef.value)
}
//封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    seckForm.value = {
        title: '',//限时秒杀名称
        begintime: '',//开始时间
        endtime: '',//结束时间
        first_cateid: '',//商品一级分类编号
        second_cateid: '',//商品二级分类编号
        goodsid: '',//商品编号
        status: 1,//状态   1正常2禁用
    }
    //清除表单验证
    formEl.resetFields()
    value2.value = []
}

const cateArr = reactive<any>({ data: [] })//二级分类

//封装一个一级分类切换事件，用于获取当前选中状态
const changeCate = (n: any) => {
    let index = store.getters['cate/getCate'].findIndex((item: any) =>
        item.id === seckForm.value.first_cateid
    )
    cateArr.data = store.getters['cate/getCate'][index].children

    //清空二级分类的双向数据绑定
    if (!n) {
        seckForm.value.second_cateid = ''
    }
}

const value2 = ref<any>([])
const size = ref<'default' | 'large' | 'small'>('default')
const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

//调用行动
const getCateAction = () => {
    store.dispatch('cate/getCateListActions')
}
getCateAction()

const getGoodsAction = () => {
    store.dispatch('goods/getGoodsListActions')
}
getGoodsAction()

const sure = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((val) => {
        if (val) {
            console.log(seckForm.value, '表单对象');
            //针对于规格属性进行数据格式转化
            let date1 = new Date(value2.value[0])
            let year1 = date1.getFullYear();
            let month1 = date1.getMonth() + 1;
            let day1 = date1.getDate();
            seckForm.value.begintime = year1 + "-" + month1 + "-" + day1
            let date2 = new Date(value2.value[1])
            let year2 = date2.getFullYear();
            let month2 = date2.getMonth() + 1;
            let day2 = date2.getDate();
            seckForm.value.endtime = year2 + "-" + month2 + "-" + day2
            // console.log(date1, year1, month1, day1,seckForm.value.begintime);
            if (props.isAdd) {
                seckAdd(seckForm.value).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('seck/getSeckListAction')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                seckEdit({ ...seckForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('seck/getSeckListAction')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' },
    ]
})

//数据回显
const lookup = (id: number) => {
    seckInfo({ id }).then(res => {
        if (res.code == 200) {
            seckForm.value = res.list
            newId = id
            changeCate(true);
            //针对于规格属性进行转化
            // $set(value2.value, 0, seckForm.value.begintime)
            // Set(value2.value, 1, seckForm.value.endtime)
            value2.value[0] = seckForm.value.begintime
            value2.value[1] = seckForm.value.endtime
        } else {
            ElMessage.error(res.msg);
        }
    })
}

defineExpose({
    lookup
})
const formLabelWidth = '140px'
</script>
<style lang='less' scoped>
.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}
</style>